
import random
from PIL import Image, ImageDraw, ImageFont, ImageFilter

def image_code():


    # 通过数字获取ascii表中的对应字母
    def get_char():

        return chr(random.randint(65, 90))

    # 获取随机颜色
    def get_color():

        return (random.randint(0, 255), random.randint(0, 255), random.randint(0, 255))

    # 创建图片对象
    img = Image.new(mode='RGB', size=(120, 50), color=get_color())

    # 创建画笔对象
    draw = ImageDraw.Draw(img, mode='RGB')

    # 噪点（干扰点）、噪线
    # 画点 xy：基于图片的坐标，fill表示点颜色
    for i in range(50):
        draw.point([random.randint(0,120), random.randint(0, 50)], fill=get_color())

    # 划线 xy:(起点坐标，终点坐标) fill：颜色  width：线宽
    # draw.line((50, 30, 100, 60),fill='purple', width=5)
    for i in range(5):
        draw.line([random.randint(0,120), random.randint(0, 50),random.randint(0,120), random.randint(0, 50)], fill=get_color())
    # 划圆或弧线
    for i in range(5):
        x = random.randint(0, 120)
        y = random.randint(0, 50)
        x2 = x + 4
        y2 = y + 4

        draw.arc((x, y, x2, y2), 0, 90, fill=get_color())

    font = ImageFont.truetype('fonts/domi.ttf', 30)

    # 用来拼接验证码字符的
    char_list = []
    for i in range(5):
        char = get_char()
        char_list.append(char)
        height = random.randint(10, 15)
        draw.text([18*(i+1), height], char, get_color(), font=font)

    char_code = ''.join(char_list)

    # 模糊效果和边缘增强效果
    # img = img.filter(ImageFilter.BLUR)
    # img = img.filter(ImageFilter.EDGE_ENHANCE_MORE)

    return img, char_code
if __name__ == '__main__':
    img, char_code = image_code()

    with open('code.png', 'wb') as f:
        # save保存图片
        img.save(f, format='png')


